#include "dlgeditworkrequest.h"
#include "main.h"
#include "pmclientdata.h"
#include "pm/manager.h"
#include "pm/project.h"
#include <boost/foreach.hpp>

DlgEditWorkRequest::DlgEditWorkRequest(wxWindow* parent, const wxString& title)
: DlgEditWorkRequestGui(parent, wxID_ANY, title)
{
	pm::ListProject listProject;
	pm::select_all(listProject);
	BOOST_FOREACH(const pm::Project& project, listProject) {
		m_listProject->Append(project.name(), new IdClientData(project.id()));
	}
	m_listProject->SetSelection(0);
}

void DlgEditWorkRequest::OnSubmit( wxCommandEvent& WXUNUSED(event) )
{
	if (TransferDataFromWindow() == false) {
		return;
	}
	
	double amount = 0;
	if (!m_sAmount.ToDouble(&amount)) {
		return;
	}
	
	const IdClientData* data = dynamic_cast<IdClientData*>(m_listProject->GetClientObject(m_listProject->GetSelection()));
	assert(data);
	
	m_workRequest.name(m_editName->GetValue());
	m_workRequest.amount(amount);
	m_workRequest.date(m_dpDate->GetValue());
	m_workRequest.id_project(data->id());

	EndModal(Submit() ? wxID_OK : wxID_CANCEL);
}

DlgNewWorkRequest::DlgNewWorkRequest(wxWindow* parent)
: DlgEditWorkRequest(parent, _("New work request"))
{
}

bool DlgNewWorkRequest::Submit()
{
	if (pm::insert(m_workRequest) == false) {
		wxLogError(_("Can't insert work request !"));
		return false;
	}
	
	pmEvent<pm::WorkRequest> evt(pmEVT_WORK_REQUEST_ADDED, m_workRequest);
	wxPostEvent(wxTheApp, evt);
	return true;
}

DlgUpdateWorkRequest::DlgUpdateWorkRequest(wxWindow* parent, const pm::WorkRequest& workRequest)
: DlgEditWorkRequest(parent, _("Update work request"))
{
	m_workRequest = workRequest;
	
	m_editName->SetValue(m_workRequest.name());
	m_sAmount.Printf(wxT("%.2f"), m_workRequest.amount());
	m_dpDate->SetValue(m_workRequest.date());
	// TODO : select project
	TransferDataToWindow();
}

bool DlgUpdateWorkRequest::Submit()
{
	if (pm::update(m_workRequest) == false) {
		wxLogError(_("Can't update work request !"));
		return false;
	}
	
	pmEvent<pm::WorkRequest> evt(pmEVT_WORK_REQUEST_UPDATED, m_workRequest);
	wxPostEvent(wxTheApp, evt);
	return true;
}
